﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Web.UI.WebControls;
using System.ComponentModel;
using System.Diagnostics;

namespace Axe.Web.Controls
{
    public abstract class EnumBoundDropDownList<T> : HardcodedDropDownList 
    {
        protected override HardcodedDropDownListEventArgs OnRequestDataItems()
        {
            HardcodedDropDownListEventArgs e = new HardcodedDropDownListEventArgs();

            string[] items = Enum.GetNames(typeof(T));

            foreach (string item in items)
            {
                ListItem li = new ListItem();
                li.Text = GetEnumItemPublicName((T)Enum.Parse(typeof(T), item));
                li.Value = item;

                li.Selected = (item == DefaultValue.ToString());

                e.BoundItems.Add(li);
            }

            return e;
        }

        public EnumBoundDropDownList()
        {
            if (typeof(T).IsEnum == false)
                throw new InvalidOperationException("T is not Enumeration");
        }

        private T m_DefaultValue;

        #region public T DefaultValue
        [Bindable(true)]
        public T DefaultValue
        {
            get { return m_DefaultValue; }
            set { m_DefaultValue = value; }
        } 
        #endregion

        #region public T SelectedEnum
        [Bindable(true, BindingDirection.TwoWay)]
        public T SelectedEnum
        {
            get
            {
                if (String.IsNullOrEmpty(SelectedValue))
                    return DefaultValue;

                try
                {
                    return (T)Enum.Parse(typeof(T), SelectedValue);
                }
                catch (Exception e)
                {
                    Debug.WriteLine(e.Message);
                    return DefaultValue;
                }
            }
            set
            {
                base.SelectedValue = value.ToString();
            }
        } 
        #endregion

        protected abstract string GetEnumItemPublicName(T item);
    }
}
